/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wust.baby.picture;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.wust.R;
import com.wust.http.FormFile;
import com.wust.http.SocketHttpRequester;




import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class Gallery1 extends Activity implements OnGestureListener{
	private Context mContext;
	private final int ICON_LIST_DIALOG = 1;
	private  Uri[] uri =GetImagesFromSDCard.uriArray;
	private  List<String> imgfile=GetImagesFromSDCard.it;
	List<Uri>urilist=new ArrayList<Uri>();
	private ViewFlipper flipper;
	private GestureDetector detector;
	int k=0;
	int position;
	private String user_name;
	private String imageName;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//影藏顶部程序名称 写在setContentView(R.layout.gallery_1);之前，不然报错
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
		setContentView(R.layout.gallery_1);
		//影藏顶部电量等图标
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		SharedPreferences preferences = getSharedPreferences("userinfo",0);
		user_name=preferences.getString("user_name", "");
		System.out.println("user_name"+user_name);
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper1);
		
		position=GetImagesFromSDCard.imagePosition;
		if(position>=0&&position<imgfile.size())
		{
			flipper.addView(addTextView(position));
			if(position!=0)
				flipper.addView(addTextView(position-1));
		}
	
		
		  	detector = new GestureDetector(this);
		  	
			

		/*	for(int i=0;i<urilist.size();i++)
			{
				
				flipper.addView(addTextView(i));
			}*/
			
	}

	 private View addTextView(int id) {
			ImageView iv = new ImageView(this);
			Bitmap dBitmap = BitmapFactory.decodeFile(imgfile.get(id));
			Drawable drawable = new BitmapDrawable(dBitmap);
			//iv.setImageURI(uri[id]);
			iv.setImageDrawable(drawable);
			return iv;
		}
	 
	    @Override
	    protected Dialog onCreateDialog(int id) {
	    	Dialog dialog = null;
	    	switch(id) {
	    		case ICON_LIST_DIALOG:
	    			Builder builder = new AlertDialog.Builder(this);
	    			BaseAdapter adapter = new ListItemAdapter();
	    			DialogInterface.OnClickListener listener = 
	    				new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialogInterface, int which) {
								/////////////////
							switch(which)
							{
								case 0:
									new Thread()
									{
										public void run()
										{
										 String photoURL=imgfile.get(position);
										 imageName=photoURL.substring(photoURL.lastIndexOf("/")+1, photoURL.length());
											Map<String, String> params = new HashMap<String, String>();
					                         params.put("fileName", imageName);
					                         params.put("user_name", user_name);
					                      
					                         File file=new File(imgfile.get(position));
					                       //  System.out.println("file:"+file.getAbsolutePath());
											 FormFile formfile = new FormFile(imageName,file , "image", "application/octet-stream");
										
											 try {
												SocketHttpRequester.post(com.wust.util.ConstDefine.URL+"uploadimageaction", params, formfile);
											} catch (Exception e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										}
									}.start();
										 break;
								case 1:
									 File file1=new File(imgfile.get(position));
				                       //  System.out.println("file:"+file.getAbsolutePath());
										file1.delete();
									imgfile.remove(position);
									if(position>=0&&position<imgfile.size()){
										flipper.showNext();
										position=position+1;
										
									}
									flipper.removeAllViews();
									
									if(position==imgfile.size())
									{
										position=imgfile.size()-1;
									}
									if(position>=0&&position<imgfile.size())
									{
										flipper.addView(addTextView(position));
										if(position!=0)
											flipper.addView(addTextView(position-1));
									}
									
									
								}
							}
						};
					builder.setAdapter(adapter, listener);
	    			dialog=builder.create();
	    			break;
	    	}
	    	return dialog;
	    }
	    class ListItemAdapter extends BaseAdapter {
			public int getCount() {
				return 2;
			}
			public Object getItem(int position) {
				return null;
			}
			public long getItemId(int position) {
				return 0;
			}
			public View getView(int position, 
					View contentView, ViewGroup parent) {
				TextView textView = 
					new TextView(Gallery1.this);
				//获得array.xml中的数组资源getStringArray返回的是一个String数组
				String text = getResources().getStringArray(R.array.selector)[position];
				textView.setText(text);
				//设置字体大小
				textView.setTextSize(24);
				AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
						LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				textView.setLayoutParams(layoutParams);
				//设置水平方向上居中
				textView.setGravity(android.view.Gravity.CENTER_VERTICAL);
				textView.setMinHeight(65);
				//设置文字颜色
				textView.setTextColor(Color.BLACK);  
				//设置textView的左上右下的padding大小
				textView.setPadding(15, 0, 15, 0);
				//设置文字和图标之间的padding大小
				textView.setCompoundDrawablePadding(15);
				return textView;
			}
			
	    	
	    }
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return this.detector.onTouchEvent(event);
	}
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		if (e1.getX() - e2.getX() > 120) {
			k++;
			System.out.println("k"+k+"pos"+position);
			this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
			this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
			
			if(position>=0&&position<imgfile.size()){
				this.flipper.showNext();
				position=position+1;
			}
			if(k==1)
			{
				
				flipper.removeAllViews();
				
				if(position==imgfile.size())
				{
					position=imgfile.size()-1;
				}
				if(position>=0&&position<imgfile.size())
				{
					flipper.addView(addTextView(position));
					if(position!=0)
						flipper.addView(addTextView(position-1));
				}
				
				k=0;
			}
	
			
			return true;
		} else if (e1.getX() - e2.getX() < -120) {
			k--;
		
			this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
			this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
			if(position>=0&&position<imgfile.size()){
				this.flipper.showPrevious();
				position=position-1;
			}
			
			if(k==-1)
			{
				//position=position-1;
				flipper.removeAllViews();
			/*	for(int i=position;i<position+1;i++)
				{
					if(i>=imgfile.size())
						i=i-imgfile.size();
					if(i<0)
						i=i+imgfile.size();
					System.out.println("i 5:"+i);
					flipper.addView(addTextView(i));
				}
				for(int i=position-1;i<position;i++)
				{
					if(i>=imgfile.size())
						i=i-imgfile.size();
					if(i<0)
						i=i+imgfile.size();
					System.out.println("i 6:"+i);
					flipper.addView(addTextView(i));
				}*/
				if(position<0)
				{
					position=0;
				}
				if(position>=0&&position<imgfile.size())
				{
					flipper.addView(addTextView(position));
					if(position!=0)
						flipper.addView(addTextView(position-1));
				}
				k=0;
			}
			
			return true;
		}
		
		return false;
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		showDialog(ICON_LIST_DIALOG);
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
}